<template>
  <div class="decision-tree-container">
    <el-container>
      <el-header height="60px">
        <h1>{{ $t('home.title') }}</h1>
        <el-select v-model="$i18n.locale">
          <el-option label="English" value="en" />
          <el-option label="中文" value="zh" />
        </el-select>
      </el-header>

      <el-main>
        <el-row :gutter="20">
          <!-- 左侧控制面板 -->
          <el-col :span="8">
            <el-card class="control-panel">
              <template #header>
                <div class="card-header">
                  <span>{{ $t('home.nodeManagement') }}</span>
                  <el-button type="primary" @click="showCreateNodeDialog = true">
                    {{ $t('home.createNode') }}
                  </el-button>
                </div>
              </template>

              <!-- 节点列表 -->
              <div class="node-list">
                <h3>{{ $t('home.createdNodes') }}</h3>
                <el-table :data="nodes" style="width: 100%">
                  <el-table-column prop="name" :label="$t('home.nodeName')" />
                  <el-table-column prop="type" :label="$t('home.type')">
                    <template #default="scope">
                      <el-tag :type="getNodeTypeColor(scope.row.type)">
                        {{ getNodeTypeName(scope.row.type) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('home.actions')">
                    <template #default="scope">
                      <el-button size="small" @click="editNode(scope.row)">{{ $t('home.edit') }}</el-button>
                      <el-button size="small" type="danger" @click="deleteNode(scope.row)">{{ $t('home.delete') }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <!-- 可视化控制 -->
              <div class="visualization-controls" style="margin-top: 20px;">
                <el-button type="success" @click="visualizeTree" :disabled="nodes.length === 0">
                  {{ $t('home.generateVisualization') }}
                </el-button>
                <el-button @click="clearVisualization">{{ $t('home.clearVisualization') }}</el-button>
                <el-button type="info" @click="loadExample" style="margin-top: 10px;">
                  {{ $t('home.loadExample') }}
                </el-button>
                <el-button type="warning" @click="exportData" :disabled="nodes.length === 0" style="margin-top: 10px;">
                  {{ $t('home.exportData') }}
                </el-button>
                <el-button type="primary" @click="importData" style="margin-top: 10px;">
                  {{ $t('home.importData') }}
                </el-button>
                <el-button type="danger" @click="generateTree" :disabled="nodes.length === 0" style="margin-top: 10px;">
                  {{ $t('home.generateDecisionTree') }}
                </el-button>
              </div>

              <!-- Payoff函数配置 -->
              <div class="payoff-config" style="margin-top: 20px;">
                <h4>{{ $t('home.payoffFunctionConfig') }}</h4>
                <el-input v-model="payoffFunction" type="textarea" :rows="12"
                  placeholder="def payoff_fn(values, probabilities, branches):&#10;    bid = values[\"bid\"] if \"bid\" in values.keys() else 0&#10;    competitor_bid = (&#10;        values[\"competitor_bid\"] &#10;        if \"competitor_bid\" in values.keys() else 0&#10;    )&#10;    cost = values[\"cost\"] if \"cost\" in values.keys() else 0&#10;    return (bid - cost) * (1 if bid < competitor_bid else 0)"
                  style="font-family: 'Courier New', monospace; font-size: 12px;" />
                <div style="margin-top: 10px;">
                  <el-button type="success" size="small" @click="savePayoffFunction">
                    {{ $t('home.saveFunction') }}
                  </el-button>
                  <el-button size="small" @click="resetPayoffFunction">
                    {{ $t('home.resetToDefault') }}
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧可视化区域 -->
          <el-col :span="16">
            <el-card class="visualization-area">
              <template #header>
                <div class="card-header">
                  <span>{{ $t('home.decisionTreeVisualization') }}</span>
                  <div class="interaction-controls">
                    <el-button size="small" @click="resetZoom" :disabled="!hasGraphviz">
                      {{ $t('home.resetZoom') }}
                    </el-button>
                    <el-button size="small" @click="fitGraph" :disabled="!hasGraphviz">
                      {{ $t('home.fitWindow') }}
                    </el-button>
                    <el-button size="small" @click="toggleZoom" :disabled="!hasGraphviz">
                      {{ zoomEnabled ? $t('home.disableZoom') : $t('home.enableZoom') }}
                    </el-button>
                  </div>
                </div>
              </template>
              <div id="tree-container" class="tree-container"></div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 创建节点对话框 -->
    <el-dialog v-model="showCreateNodeDialog" :title="$t('home.createNodeTitle')" width="600px">
      <el-form :model="newNode" label-width="120px">
        <el-form-item :label="$t('home.nodeNameLabel')">
          <el-input v-model="newNode.name" :placeholder="$t('home.nodeNamePlaceholder')" />
        </el-form-item>

        <el-form-item :label="$t('home.nodeTypeLabel')">
          <el-select v-model="newNode.type" :placeholder="$t('home.nodeTypePlaceholder')">
            <el-option :label="$t('home.decisionNode')" value="decision" />
            <el-option :label="$t('home.chanceNode')" value="chance" />
            <el-option :label="$t('home.terminalNode')" value="terminal" />
          </el-select>
        </el-form-item>

        <!-- 决策节点配置 -->
        <template v-if="newNode.type === 'decision'">
          <el-form-item :label="$t('home.maximize')">
            <el-switch v-model="newNode.maximize" />
          </el-form-item>

          <el-form-item :label="$t('home.branchConfig')">
            <div v-for="(branch, index) in newNode.branches" :key="index" class="branch-item">
              <div class="branch-form">
                <el-form-item :label="$t('home.branchName')" label-width="80px">
                  <el-input v-model="branch.name" :placeholder="$t('home.branchNamePlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.value')" label-width="80px">
                  <el-input v-model="branch.value" :placeholder="$t('home.valuePlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.targetNode')" label-width="80px">
                  <el-input v-model="branch.target" :placeholder="$t('home.targetNodePlaceholder')" />
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" size="small" @click="removeBranch(index)">{{ $t('home.deleteBranch') }}</el-button>
                </el-form-item>
              </div>
            </div>
            <el-button type="primary" size="small" @click="addBranch">{{ $t('home.addBranch') }}</el-button>
          </el-form-item>
        </template>

        <!-- 机会节点配置 -->
        <template v-if="newNode.type === 'chance'">
          <el-form-item :label="$t('home.branchConfig')">
            <div v-for="(branch, index) in newNode.branches" :key="index" class="branch-item">
              <div class="branch-form">
                <el-form-item :label="$t('home.branchName')" label-width="80px">
                  <el-input v-model="branch.name" :placeholder="$t('home.branchNamePlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.probability')" label-width="80px">
                  <el-input v-model="branch.probability" :placeholder="$t('home.probabilityPlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.value')" label-width="80px">
                  <el-input v-model="branch.value" :placeholder="$t('home.valuePlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.targetNode')" label-width="80px">
                  <el-input v-model="branch.target" :placeholder="$t('home.targetNodePlaceholder')" />
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" size="small" @click="removeBranch(index)">{{ $t('home.deleteBranch') }}</el-button>
                </el-form-item>
              </div>
            </div>
            <el-button type="primary" size="small" @click="addBranch">{{ $t('home.addBranch') }}</el-button>
          </el-form-item>
        </template>

        <!-- 结束节点配置 -->
        <template v-if="newNode.type === 'terminal'">
          <el-form-item :label="$t('home.payoffFunction')">
            <el-input v-model="newNode.payoffFn" :placeholder="$t('home.payoffFunctionName')" />
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateNodeDialog = false">{{ $t('home.cancel') }}</el-button>
          <el-button type="primary" @click="createNode">{{ $t('home.create') }}</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑节点对话框 -->
    <el-dialog v-model="showEditNodeDialog" :title="$t('home.editNodeTitle')" width="600px">
      <el-form :model="editingNode" label-width="120px">
        <el-form-item :label="$t('home.nodeNameLabel')">
          <el-input v-model="editingNode.name" :placeholder="$t('home.nodeNamePlaceholder')" />
        </el-form-item>

        <el-form-item :label="$t('home.nodeTypeLabel')">
          <el-select v-model="editingNode.type" :placeholder="$t('home.nodeTypePlaceholder')" disabled>
            <el-option :label="$t('home.decisionNode')" value="decision" />
            <el-option :label="$t('home.chanceNode')" value="chance" />
            <el-option :label="$t('home.terminalNode')" value="terminal" />
          </el-select>
        </el-form-item>

        <!-- 决策节点配置 -->
        <template v-if="editingNode.type === 'decision'">
          <el-form-item :label="$t('home.maximize')">
            <el-switch v-model="editingNode.maximize" />
          </el-form-item>

          <el-form-item :label="$t('home.branchConfig')">
            <div v-for="(branch, index) in editingNode.branches" :key="index" class="branch-item">
              <div class="branch-form">
                <el-form-item :label="$t('home.branchName')" label-width="80px">
                  <el-input v-model="branch.name" :placeholder="$t('home.branchNamePlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.value')" label-width="80px">
                  <el-input v-model="branch.value" :placeholder="$t('home.valuePlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.targetNode')" label-width="80px">
                  <el-input v-model="branch.target" :placeholder="$t('home.targetNodePlaceholder')" />
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" size="small" @click="removeEditBranch(index)">{{ $t('home.deleteBranch') }}</el-button>
                </el-form-item>
              </div>
            </div>
            <el-button type="primary" size="small" @click="addEditBranch">{{ $t('home.addBranch') }}</el-button>
          </el-form-item>
        </template>

        <!-- 机会节点配置 -->
        <template v-if="editingNode.type === 'chance'">
          <el-form-item :label="$t('home.branchConfig')">
            <div v-for="(branch, index) in editingNode.branches" :key="index" class="branch-item">
              <div class="branch-form">
                <el-form-item :label="$t('home.branchName')" label-width="80px">
                  <el-input v-model="branch.name" :placeholder="$t('home.branchNamePlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.probability')" label-width="80px">
                  <el-input v-model="branch.probability" :placeholder="$t('home.probabilityPlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.value')" label-width="80px">
                  <el-input v-model="branch.value" :placeholder="$t('home.valuePlaceholder')" />
                </el-form-item>
                <el-form-item :label="$t('home.targetNode')" label-width="80px">
                  <el-input v-model="branch.target" :placeholder="$t('home.targetNodePlaceholder')" />
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" size="small" @click="removeEditBranch(index)">{{ $t('home.deleteBranch') }}</el-button>
                </el-form-item>
              </div>
            </div>
            <el-button type="primary" size="small" @click="addEditBranch">{{ $t('home.addBranch') }}</el-button>
          </el-form-item>
        </template>

        <!-- 结束节点配置 -->
        <template v-if="editingNode.type === 'terminal'">
          <el-form-item :label="$t('home.payoffFunction')">
            <el-input v-model="editingNode.payoffFn" :placeholder="$t('home.payoffFunctionName')" />
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditNodeDialog = false">{{ $t('home.cancel') }}</el-button>
          <el-button type="primary" @click="saveNodeEdit">{{ $t('home.save') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

// 响应式数据
const nodes = ref([])
const showCreateNodeDialog = ref(false)
const showEditNodeDialog = ref(false)
const editingNodeIndex = ref(-1)
const payoffFunction = ref('')
const hasGraphviz = ref(false)
const zoomEnabled = ref(true)
const currentGraphviz = ref(null)

// 新节点数据
const newNode = reactive({
  name: '',
  type: 'decision',
  maximize: true,
  branches: [],
  payoffFn: ''
})

// 编辑节点数据
const editingNode = reactive({
  name: '',
  type: 'decision',
  maximize: true,
  branches: [],
  payoffFn: ''
})

// 初始化新节点
const initNewNode = () => {
  newNode.name = ''
  newNode.type = 'decision'
  newNode.maximize = true
  newNode.branches = []
  newNode.payoffFn = ''
}

// 添加分支
const addBranch = () => {
  if (newNode.type === 'decision') {
    newNode.branches.push({ name: '', value: '', target: '' })
  } else if (newNode.type === 'chance') {
    newNode.branches.push({ name: '', probability: '', value: '', target: '' })
  }
}

// 移除分支
const removeBranch = (index) => {
  newNode.branches.splice(index, 1)
}

// 添加编辑分支
const addEditBranch = () => {
  if (editingNode.type === 'decision') {
    editingNode.branches.push({ name: '', value: '', target: '' })
  } else if (editingNode.type === 'chance') {
    editingNode.branches.push({ name: '', probability: '', value: '', target: '' })
  }
}

// 移除编辑分支
const removeEditBranch = (index) => {
  editingNode.branches.splice(index, 1)
}

// 创建节点
const createNode = () => {
  if (!newNode.name) {
    ElMessage.error(t('home.enterNodeName'))
    return
  }

  if (nodes.value.find(n => n.name === newNode.name)) {
    ElMessage.error(t('home.nodeNameExists'))
    return
  }

  const node = {
    name: newNode.name,
    type: newNode.type,
    maximize: newNode.maximize,
    branches: [...newNode.branches],
    payoffFn: newNode.payoffFn
  }

  nodes.value.push(node)
  showCreateNodeDialog.value = false
  initNewNode()
  ElMessage.success(t('home.nodeCreatedSuccessfully'))
}

// 编辑节点
const editNode = (node) => {
  const index = nodes.value.findIndex(n => n.name === node.name)
  if (index !== -1) {
    editingNodeIndex.value = index
    Object.assign(editingNode, JSON.parse(JSON.stringify(node)))
    showEditNodeDialog.value = true
  }
}

// 保存节点编辑
const saveNodeEdit = () => {
  if (!editingNode.name) {
    ElMessage.error(t('home.enterNodeName'))
    return
  }

  const existingIndex = nodes.value.findIndex(n => n.name === editingNode.name && n.name !== nodes.value[editingNodeIndex.value].name)
  if (existingIndex !== -1) {
    ElMessage.error(t('home.nodeNameExists'))
    return
  }

  nodes.value[editingNodeIndex.value] = JSON.parse(JSON.stringify(editingNode))
  showEditNodeDialog.value = false
  ElMessage.success(t('home.nodeEditedSuccessfully'))
}

// 删除节点
const deleteNode = (node) => {
  ElMessageBox.confirm(t('home.confirmDeleteNode'), t('home.prompt'), {
    confirmButtonText: t('home.confirm'),
    cancelButtonText: t('home.cancel'),
    type: 'warning'
  }).then(() => {
    const index = nodes.value.findIndex(n => n.name === node.name)
    if (index !== -1) {
      nodes.value.splice(index, 1)
      ElMessage.success(t('home.nodeDeletedSuccessfully'))
    }
  })
}

// 获取节点类型颜色
const getNodeTypeColor = (type) => {
  const colors = {
    decision: 'primary',
    chance: 'success',
    terminal: 'warning'
  }
  return colors[type] || 'info'
}

// 获取节点类型名称
const getNodeTypeName = (type) => {
  const names = {
    decision: t('home.decisionNodeType'),
    chance: t('home.chanceNodeType'),
    terminal: t('home.terminalNodeType')
  }
  return names[type] || type
}

// 可视化决策树
const visualizeTree = () => {
  if (nodes.value.length === 0) {
    ElMessage.warning(t('home.pleaseCreateNodesFirst'))
    return
  }

  // 清除现有可视化
  const container = document.getElementById('tree-container')
  container.innerHTML = ''

  // 构建ECharts树形数据
  const treeData = buildEChartsTreeData()

  // 创建ECharts实例
  const chart = echarts.init(container)

  // 配置选项
  const option = {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ccc',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: function (params) {
        if (params.data.type === 'node') {
          let tooltip = `<div style="font-weight: bold; margin-bottom: 5px;">${params.data.name}</div>`
          tooltip += `<div style="color: #666;">${t('home.typeLabel')}${getNodeTypeName(params.data.nodeType)}</div>`
          if (params.data.branchInfo) {
            tooltip += `<div style="color: #666; margin-top: 3px;">${t('home.attributesLabel')}${params.data.branchInfo}</div>`
          }
          return tooltip
        }
        return params.data.name
      }
    },
    series: [
      {
        type: 'tree',
        data: [treeData],
        top: '8%',
        left: '10%',
        bottom: '5%',
        right: '25%',
        symbolSize: function (value, params) {
          // 根据节点类型设置不同大小
          const nodeType = params.data.nodeType
          if (nodeType === 'decision') return 20
          if (nodeType === 'chance') return 18
          if (nodeType === 'terminal') return 16
          return 16
        },
        orient: 'vertical',
        label: {
          position: 'left',
          verticalAlign: 'middle',
          align: 'right',
          fontSize: 11,
          lineHeight: 16,
          padding: [4, 8],
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          borderRadius: 4,
          formatter: function (params) {
            // 如果是分支节点，显示分支信息
            if (params.data.branchInfo) {
              return `${params.data.name}\n${params.data.branchInfo}`
            }
            return params.data.name
          }
        },
        leaves: {
          label: {
            position: 'right',
            verticalAlign: 'middle',
            align: 'left',
            fontSize: 11,
            lineHeight: 16,
            padding: [4, 8],
            backgroundColor: 'rgba(255, 255, 255, 0.8)',
            borderRadius: 4
          }
        },
        emphasis: {
          focus: 'descendant',
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        },
        expandAndCollapse: true,
        animationDuration: 550,
        animationDurationUpdate: 750,
        initialTreeDepth: -1,
        lineStyle: {
          color: '#999',
          width: 2,
          curveness: 0.1
        },
        itemStyle: {
          color: function (params) {
            return getNodeColor(params.data.nodeType)
          },
          borderColor: '#333',
          borderWidth: 2,
          borderRadius: function (params) {
            // 根据节点类型设置不同圆角
            const nodeType = params.data.nodeType
            if (nodeType === 'decision') return 8
            if (nodeType === 'chance') return 6
            if (nodeType === 'terminal') return 4
            return 4
          }
        }
      }
    ]
  }

  // 设置配置并渲染
  chart.setOption(option)

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })

  ElMessage.success(t('home.visualizationGeneratedSuccessfully'))
}

// 构建ECharts树形数据
const buildEChartsTreeData = () => {
  const nodeMap = new Map()
  const allNodes = new Set()

  // 收集所有节点名称（包括目标节点）
  nodes.value.forEach(node => {
    allNodes.add(node.name)
    if (node.branches) {
      node.branches.forEach(branch => {
        if (branch.target) {
          allNodes.add(branch.target)
        }
      })
    }
  })

  // 创建所有节点的映射
  allNodes.forEach(nodeName => {
    const existingNode = nodes.value.find(n => n.name === nodeName)
    if (existingNode) {
      nodeMap.set(nodeName, {
        name: nodeName,
        type: 'node',
        nodeType: existingNode.type,
        children: [],
        branches: existingNode.branches
      })
    } else {
      // 自动创建缺失的目标节点
      nodeMap.set(nodeName, {
        name: nodeName,
        type: 'node',
        nodeType: 'terminal', // 默认为结束节点
        children: [],
        branches: []
      })
    }
  })

  // 构建连接关系
  nodes.value.forEach(node => {
    if (node.branches) {
      node.branches.forEach(branch => {
        if (branch.target) {
          const targetNode = nodeMap.get(branch.target)
          const sourceNode = nodeMap.get(node.name)
          if (targetNode && sourceNode) {
            // 创建分支标签
            let label = branch.name
            let attributes = []

            if (branch.value !== undefined && branch.value !== null && branch.value !== '') {
              attributes.push(`${t('home.valueLabel')}${branch.value}`)
            }
            if (branch.probability !== undefined && branch.probability !== null && branch.probability !== '') {
              const prob = parseFloat(branch.probability)
              if (!isNaN(prob)) {
                attributes.push(`${t('home.probabilityLabel')}${(prob * 100).toFixed(1)}%`)
              }
            }

            const childNode = {
              ...targetNode,
              name: `${label} → ${targetNode.name}`,
              branchInfo: attributes.join(', ')
            }

            sourceNode.children.push(childNode)
          }
        }
      })
    }
  })

  // 找到根节点（没有父节点的节点）
  const childNodes = new Set()
  nodes.value.forEach(node => {
    if (node.branches) {
      node.branches.forEach(branch => {
        if (branch.target) {
          childNodes.add(branch.target)
        }
      })
    }
  })

  // 找到根节点
  const rootNodes = []
  nodes.value.forEach(node => {
    if (!childNodes.has(node.name)) {
      const rootNode = nodeMap.get(node.name)
      if (rootNode) {
        rootNodes.push(rootNode)
      }
    }
  })

  // 如果没有找到根节点，使用第一个节点作为根节点
  if (rootNodes.length === 0 && nodes.value.length > 0) {
    const firstNode = nodeMap.get(nodes.value[0].name)
    if (firstNode) {
      rootNodes.push(firstNode)
    }
  }

  return rootNodes[0] || { name: 'root', type: 'node', nodeType: 'terminal', children: [] }
}

// 获取节点颜色
const getNodeColor = (type) => {
  const colors = {
    decision: '#1890FF', // 更深的蓝色
    chance: '#52C41A',   // 更深的绿色
    terminal: '#FA8C16'  // 更深的橙色
  }
  return colors[type] || '#8C8C8C'
}

// 清除可视化
const clearVisualization = () => {
  const container = document.getElementById('tree-container')
  container.innerHTML = ''
  ElMessage.success(t('home.visualizationCleared'))
}

// 加载示例
const loadExample = () => {
  nodes.value = [
    {
      name: 'bid',
      type: 'decision',
      maximize: true,
      branches: [
        { name: 'low', value: '300', target: 'competitor_bid' },
        { name: 'medium', value: '500', target: 'competitor_bid' },
        { name: 'high', value: '700', target: 'competitor_bid' },
        { name: 'no-bid', value: '0', target: 'profit' }
      ]
    },
    {
      name: 'competitor_bid',
      type: 'chance',
      branches: [
        { name: 'low', probability: '0.35', value: '400', target: 'cost' },
        { name: 'medium', probability: '0.50', value: '600', target: 'cost' },
        { name: 'high', probability: '0.15', value: '800', target: 'cost' }
      ]
    },
    {
      name: 'cost',
      type: 'chance',
      branches: [
        { name: 'low', probability: '0.25', value: '200', target: 'profit' },
        { name: 'medium', probability: '0.50', value: '400', target: 'profit' },
        { name: 'high', probability: '0.25', value: '600', target: 'profit' }
      ]
    },
    {
      name: 'profit',
      type: 'terminal',
      payoffFn: 'payoff_fn'
    }
  ]

  ElMessage.success(t('home.exampleDataLoadedSuccessfully'))
}

// 导出数据
const exportData = () => {
  if (nodes.value.length === 0) {
    ElMessage.warning(t('home.noDataToExport'))
    return
  }

  // 转换数据格式
  const exportNodes = nodes.value.map(node => {
    // 确保branches存在且是数组
    const branches = (node.branches && Array.isArray(node.branches))
      ? node.branches.map(branch => {
        const exportBranch = {
          label: branch.name || '',
          next: branch.target || ''
        }

        // 添加值（如果存在）
        if (branch.value !== undefined && branch.value !== null && branch.value !== '') {
          exportBranch.value = parseFloat(branch.value) || branch.value
        }

        // 添加概率（如果存在）
        if (branch.probability !== undefined && branch.probability !== null && branch.probability !== '') {
          exportBranch.probability = parseFloat(branch.probability) || branch.probability
        }

        return exportBranch
      })
      : []

    return {
      name: node.name || '',
      type: node.type || 'terminal',
      branches: branches
    }
  })

  // 创建导出数据对象
  const exportDataObj = {
    nodes: exportNodes,
    payoff_function: payoffFunction.value
  }

  // 转换为JSON字符串
  const jsonString = JSON.stringify(exportDataObj, null, 2)

  // 创建Blob对象
  const blob = new Blob([jsonString], { type: 'application/json' })

  // 创建下载链接
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = 'decision_tree_data.json'

  // 触发下载
  document.body.appendChild(link)
  link.click()

  // 清理
  document.body.removeChild(link)
  URL.revokeObjectURL(url)

  ElMessage.success(t('home.dataExportedSuccessfully'))
}

// 导入数据
const importData = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'

  input.onchange = (event) => {
    const file = event.target.files[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target.result)

        if (!data.nodes || !Array.isArray(data.nodes)) {
          ElMessage.error(t('home.incorrectFileFormat'))
          return
        }

        // 转换导入的数据格式
        const importedNodes = data.nodes.map(node => {
          // 确保branches存在且是数组
          const branches = (node.branches && Array.isArray(node.branches))
            ? node.branches.map(branch => {
              const importBranch = {
                name: branch.label || '',
                target: branch.next || ''
              }

              // 添加值（如果存在）
              if (branch.value !== undefined) {
                importBranch.value = branch.value.toString()
              }

              // 添加概率（如果存在）
              if (branch.probability !== undefined) {
                importBranch.probability = branch.probability.toString()
              }

              return importBranch
            })
            : []

          return {
            name: node.name || '',
            type: node.type || 'terminal',
            maximize: node.type === 'decision' ? true : undefined,
            branches: branches,
            payoffFn: node.type === 'terminal' ? 'payoff_fn' : ''
          }
        })

        // 更新节点数据
        nodes.value = importedNodes

        // 导入payoff函数（如果存在）
        if (data.payoff_function) {
          payoffFunction.value = data.payoff_function
        }

        ElMessage.success(t('home.dataImportedSuccessfully'))
      } catch (error) {
        ElMessage.error(`${t('home.fileParsingFailed')}${error.message}`)
      }
    }

    reader.readAsText(file)
  }

  input.click()
}

// 生成决策树
const generateTree = async () => {
  if (nodes.value.length === 0) {
    ElMessage.warning(t('home.pleaseCreateNodesFirst'))
    return
  }

  if (!payoffFunction.value.trim()) {
    ElMessage.warning(t('home.pleaseConfigurePayoffFunction'))
    return
  }

  try {
    // 准备请求数据
    const requestData = {
      json_data: {
        nodes: nodes.value.map(node => {
          const branches = (node.branches && Array.isArray(node.branches))
            ? node.branches.map(branch => {
              const exportBranch = {
                label: branch.name || '',
                next: branch.target || ''
              }

              if (branch.value !== undefined && branch.value !== null && branch.value !== '') {
                exportBranch.value = parseFloat(branch.value) || branch.value
              }

              if (branch.probability !== undefined && branch.probability !== null && branch.probability !== '') {
                exportBranch.probability = parseFloat(branch.probability) || branch.probability
              }

              return exportBranch
            })
            : []

          return {
            name: node.name || '',
            type: node.type || 'terminal',
            branches: branches
          }
        })
      },
      payoff_fn_code: payoffFunction.value
    }

    ElMessage.info(t('home.generatingDecisionTree'))

    // 调用API
    const response = await axios.post('http://localhost:8000/api/generate-tree', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data && response.data.success && response.data.dot_content) {
      // 渲染dot文件
      renderDotGraph(response.data.dot_content)
      ElMessage.success(t('home.decisionTreeGeneratedSuccessfully'))
    } else {
      const errorMessage = response.data?.message || t('home.apiErrorFormat')
      ElMessage.error(errorMessage)
    }

  } catch (error) {
    console.error(t('home.decisionTreeGenerationFailed'), error)
    ElMessage.error(`${t('home.decisionTreeGenerationFailed')} ${error.response?.data?.detail || error.message}`)
  }
}

// 渲染dot图
const renderDotGraph = async (dotContent) => {
  try {
    // 动态加载d3和d3-graphviz
    const d3 = await import('d3')
    const d3Graphviz = await import('d3-graphviz')

    // 清除容器
    const container = document.getElementById('tree-container')
    container.innerHTML = ''

    // 创建graphviz渲染器
    const graphviz = d3Graphviz.graphviz(container)
      .width(container.clientWidth)
      .height(container.clientHeight)
      .fit(true)
      .zoom(zoomEnabled.value)
      .attributer(function (d) {
        // 为节点添加交互样式
        if (d.tag === "ellipse" || d.tag === "polygon") {
          d3.select(this)
            .style("cursor", "pointer")
            .style("stroke-width", "2")
            .on("mouseover", function () {
              d3.select(this)
                .style("stroke-width", "3")
                .style("stroke", "#409eff")
                .style("opacity", "0.8")
            })
            .on("mouseout", function () {
              d3.select(this)
                .style("stroke-width", "2")
                .style("stroke", "#333")
                .style("opacity", "1")
            })
            .on("click", function () {
              // 点击节点时显示信息
              const nodeName = d3.select(this.parentNode).select("text").text()
              if (nodeName) {
                ElMessage.info(`${t('home.clickedNode')}${nodeName}`)
              }
            })
        }

        // 为边添加交互样式
        if (d.tag === "path" && d.class === "edge") {
          d3.select(this)
            .style("cursor", "pointer")
            .style("stroke-width", "2")
            .on("mouseover", function () {
              d3.select(this)
                .style("stroke-width", "3")
                .style("stroke", "#409eff")
                .style("opacity", "0.8")
            })
            .on("mouseout", function () {
              d3.select(this)
                .style("stroke-width", "2")
                .style("stroke", "#333")
                .style("opacity", "1")
            })
            .on("click", function () {
              // 点击边时显示信息
              const edgeLabel = d3.select(this.parentNode).select("text").text()
              if (edgeLabel) {
                ElMessage.info(`${t('home.clickedEdge')}${edgeLabel}`)
              }
            })
        }

        // 为文本添加交互样式
        if (d.tag === "text") {
          d3.select(this)
            .style("cursor", "pointer")
            .style("font-weight", "normal")
            .on("mouseover", function () {
              d3.select(this)
                .style("font-weight", "bold")
                .style("fill", "#409eff")
            })
            .on("mouseout", function () {
              d3.select(this)
                .style("font-weight", "normal")
                .style("fill", "#333")
            })
        }
      })

    // 渲染dot内容
    await graphviz.renderDot(dotContent)

    // 保存graphviz实例
    currentGraphviz.value = graphviz
    hasGraphviz.value = true

    ElMessage.success(t('home.decisionTreeRenderedSuccessfully'))

  } catch (error) {
    console.error(t('home.decisionTreeRenderingFailed'), error)
    ElMessage.error(`${t('home.decisionTreeRenderingFailed')} ${error.message}`)
  }
}

// 默认payoff函数
const defaultPayoffFunction = `def payoff_fn(values, probabilities, branches):
    bid = values[\"bid\"] if \"bid\" in values.keys() else 0
    competitor_bid = (
        values[\"competitor_bid\"] 
        if \"competitor_bid\" in values.keys() else 0
    )
    cost = values[\"cost\"] if \"cost\" in values.keys() else 0
    return (bid - cost) * (1 if bid < competitor_bid else 0)`

// 保存payoff函数
const savePayoffFunction = () => {
  if (!payoffFunction.value.trim()) {
    ElMessage.warning(t('home.pleaseEnterPayoffFunction'))
    return
  }

  // 这里可以添加函数语法验证
  try {
    // 简单的语法检查：确保包含def关键字
    if (!payoffFunction.value.includes('def ')) {
      throw new Error(t('home.functionMustStartWithDef'))
    }

    ElMessage.success(t('home.payoffFunctionSavedSuccessfully'))
  } catch (error) {
    ElMessage.error(`${t('home.fileParsingFailed')}${error.message}`)
  }
}

// 重置为默认函数
const resetPayoffFunction = () => {
  payoffFunction.value = defaultPayoffFunction
  ElMessage.success(t('home.resetToDefaultFunction'))
}

// 交互控制函数
const resetZoom = () => {
  if (currentGraphviz.value) {
    currentGraphviz.value.resetZoom()
    ElMessage.success(t('home.zoomReset'))
  }
}

const fitGraph = () => {
  if (currentGraphviz.value) {
    currentGraphviz.value.fit()
    ElMessage.success(t('home.graphFittedToWindow'))
  }
}

const toggleZoom = () => {
  if (currentGraphviz.value) {
    zoomEnabled.value = !zoomEnabled.value
    if (zoomEnabled.value) {
      currentGraphviz.value.zoom(true)
    } else {
      currentGraphviz.value.zoom(false)
    }
    ElMessage.success(zoomEnabled.value ? t('home.zoomEnabled') : t('home.zoomDisabled'))
  }
}

// 组件挂载时初始化
onMounted(() => {
  initNewNode()
  // 设置默认的payoff函数
  payoffFunction.value = defaultPayoffFunction
})
</script>

<style scoped>
.decision-tree-container {
  height: 100vh;
  background-color: #f5f5f5;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-header h1 {
  margin: 0;
  color: #303133;
}

.control-panel {
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.visualization-area {
  height: calc(100vh - 120px);
}

.tree-container {
  height: calc(100vh - 200px);
  overflow: hidden;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.interaction-controls {
  display: flex;
  gap: 8px;
}

.interaction-controls .el-button {
  margin: 0;
}

.node-list {
  margin-bottom: 20px;
}

.node-list h3 {
  margin-bottom: 10px;
  color: #303133;
}

.branch-item {
  margin-bottom: 10px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.branch-item .el-input-number {
  width: 100%;
}

.branch-item .el-input-number .el-input__inner {
  text-align: center;
}

.branch-form {
  padding: 10px;
}

.branch-form .el-form-item {
  margin-bottom: 15px;
}

.branch-form .el-form-item:last-child {
  margin-bottom: 0;
}

.visualization-controls {
  border-top: 1px solid #e4e7ed;
  padding-top: 20px;
}

.visualization-controls .el-button {
  margin-right: 10px;
}

.payoff-config h4 {
  margin-bottom: 10px;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.payoff-config .el-textarea__inner {
  font-family: 'Courier New', 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  line-height: 1.4;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
}

.payoff-config .el-textarea__inner:focus {
  background-color: #fff;
  border-color: #409eff;
}

/* Dot图样式 */
#tree-container svg {
  width: 100% !important;
  height: 100% !important;
  border: none;
  border-radius: 8px;
  background-color: #fff;
  margin: 0;
}

#tree-container svg text {
  font-family: 'Arial', sans-serif;
  font-size: 12px;
}

#tree-container svg .node {
  cursor: pointer;
}

#tree-container svg .edge {
  stroke-width: 2;
}
</style>